﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class User_Login : System.Web.UI.UserControl
{

    string salt = string.Empty;
    RegistrationData regdata = new RegistrationData();
    BusinessLogic busin = new BusinessLogic();
    const string constUser = "User";
    public string FName = string.Empty, LName = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!object.Equals(Session[constUser], null))
            {
                divPostLogin.Visible = true;
                divPreLogin.Visible = false;
                regdata = Session[constUser] as RegistrationData;
                FName = regdata.FirstName;
                LName = regdata.LastName;
                imgUserImage.Attributes.Add("src", regdata.ProfileImage);
            }
            else
            {
                divPostLogin.Visible = false;
                divPreLogin.Visible = true;
            }
        }
        else
        {
            if (Request.Form["__EVENTTARGET"].ToLower() == "resend")
            {
                if (Request.Form["__EVENTARGUMENT"] != null)
                {
                    string args = Request.Form["__EVENTARGUMENT"].ToString().ToLower();
                    int num = 0;
                    if (Int32.TryParse(args, out num))
                    {
                        ResendEmail(num);
                    }
                }
                lblMessage.Text = "We have sent you an email please verify and then try to  login.";
            }
        }
    }

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        if (validation())
        {
            string password = string.Empty;
            SqlDataReader dr;
            dr = regdata.SelectUserDetails_Email(txtusername.Text);
            if (dr.Read())
            {
                if (dr["Salt"] != DBNull.Value)
                    salt = dr["Salt"].ToString();
            }
            dr.Close();
            password = regdata.protectpassword(regdata.protectpassword(txtpassword.Text) + salt);
            DataSet ds = new DataSet();
            ds = regdata.SelectUserLoginDetails(txtusername.Text, password);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr1 = ds.Tables[0].Rows[0];
                    if (Convert.ToInt32(dr1["IsActive"]) == 1)
                    {
                        if (Convert.ToInt32(dr1["ActivatedByEmail"]) == 1)
                        {
                            divPostLogin.Visible = true;
                            divPreLogin.Visible = false;
                            busin.InsertSession(ds, chkRemember.Checked);
                            Response.Redirect(Request.RawUrl.ToString());
                        }
                        else
                        {
                            lblMessage.Text = "Your Email is not verified yet.If you did not receive, you can <a href=javascript:__doPostBack('resend','"+Convert.ToString(dr1["USerID"])+"') >Resend Email</a> ";
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Your Account has been deactivated";
                    }
                }
                else
                {
                    lblMessage.Text = "Invalid Email/User Name or Password";
                    txtpassword.Text = "";
                }
            }
            else
            {
                lblMessage.Text = "Invalid Email/User Name or Password";
                txtpassword.Text = "";
            }
        }
    }

    void ResendEmail( int UserID)
    {
        DataSet registration = new DataSet();
        registration = regdata.GetUserID(UserID);
        if (registration != null)
        {
            if (registration.Tables.Count > 0)
            {
                if (registration.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = registration.Tables[0].Rows[0];
                    SendEmails auto = new SendEmails();
                    EmailData.UserName = dr["UserName"].ToString();
                    EmailData.Name = dr["FirstName"].ToString();

                    RegexValidator rv = new RegexValidator();
                    string strConfig = string.Empty;
                    strConfig = EmailData.WebsiteLink;
                    string Link = strConfig + "ActivateAccount.aspx?id=";
                    string strCode = DateTime.Now.ToString("MM/dd/yyyyhh:mm:ss:fff");
                    strCode = rv.RemoveSpecialChar1(strCode);
                    strCode = strCode + "-" + Convert.ToString(dr["UserID"]);
                    Link = Link + strCode;
                    regdata.Update_EmailVerificationLink(Convert.ToInt32(dr["UserID"]), Link);
                    string subject = EmailData.WebsiteAdmin + " - Activate Account";
                    EmailData.Link = Link;
                    auto.GeneralEmail(subject, dr["Email"].ToString(), 1);
                }
            }
        }
    }
    bool validation()
    {
        if (txtusername.Text == string.Empty)
        {
            lblMessage.Text = "Please Enter Email/User Name";
            return false;
        }
        if (txtpassword.Text == string.Empty)
        {
            lblMessage.Text = "Please Enter Password";
            return false;
        }
        return true;
    }

    protected void lnksngup_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Registration.aspx");
    }

    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        busin.LogOut();
    } 
}